package com.sgcc.pda.web.upload.manager;

import android.util.Log;

import com.sgcc.pda.baselibrary.ConstPath;
import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.web.IHttpCallbackInterface;
import com.sgcc.pda.web.service.ZoomWebControler;
import com.sgcc.pda.web.upload.entity.BlockUploadTaskEvent;
import com.sgcc.pda.web.upload.listener.UploadListener;

//import org.greenrobot.eventbus.EventBus;
//import org.greenrobot.eventbus.Subscribe;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author zcj
 * @date 2019/10/4
 * <p>
 * 针对多个文件封装
 * <p>
 * 将每个文件上传请求进行存储为Map,键名为文件路径
 * 当收到取消上传时，将此文件所有异步任务取消。
 */
public class UploadManager {

    private static final String TAG = "cj";

    private static UploadManager instance;

    private List<UploadTask> doingQueue = new ArrayList<>();
    private List<UploadTask> waitingQueue = new ArrayList<>();
    private int taskCounts = 2;

    public static UploadManager getInstance() {
        synchronized (UploadManager.class) {
            if (instance == null) {
                instance = new UploadManager();
            }
            return instance;
        }
    }

    private UploadManager() {
        EventBus.getDefault().register(this);
    }

    /**
     * 1、先入等待队列
     * 2、再入执行集合
     * 3、收到执行完毕，doNext
     */
    public void upload(String filePath, String savePath, long blockSize, String origionFilePath, boolean isDelete, UploadListener listener) {
        File file = new File(filePath);
        UploadTask uploadTask = new UploadTask(file, savePath, blockSize, origionFilePath, isDelete, listener);

        waitingQueue.add(uploadTask);

        if (doingQueue.size() < taskCounts) {
            UploadTask task = pollTask();
            Log.e(TAG, "waittttttingSize: " + waitingQueue.size());
            if (task != null) {
                doingQueue.add(task);
                Log.e(TAG, "doingSize: " + doingQueue.size());
                task.startUpload();
            }
        } else {

            //等待中
            uploadTask.getListener().progress(0, 0, 3);

        }
    }


    /**
     * 从待执行队列拿一个放到执行队列开始执行
     */
    public void doNext() {
        UploadTask uploadTask = pollTask();
        Log.e(TAG, "waittttttingSize: " + waitingQueue.size());
        if (uploadTask != null) {
            Log.e(TAG, "从waiting拿出一个放入doing，开始执行");
            doingQueue.add(uploadTask);
            Log.e(TAG, "doingSize: " + doingQueue.size());
            uploadTask.startUpload();
        }
    }

    public void cancelUpload(String filePath, String savePath, IHttpCallbackInterface httpCallbackInterface) {
        //生成zip名字
        File file = new File(filePath);
        String name = file.getName();
        String zipFilePath = ConstPath.BLOCK_UPLOAD_ZIP_PATH + name + ".zip";

        cancelLocal(zipFilePath);
        cancelServer(zipFilePath, savePath, httpCallbackInterface);
    }

    public void cancelLocal(String filePath) {
        //本地停止
        //是否正在执行doing，（删除的doing列表 + 停止所有异步任务）
        //是否wating，（直接删除列表里的uploadtask）

        Iterator<UploadTask> iterator = doingQueue.iterator();
        while (iterator.hasNext()) {
            UploadTask uploadTask = iterator.next();
            if (uploadTask.getZipFilePath().equals(filePath)) {
                LogUtil.e(TAG, "找到doing任务，开始停止" + filePath);
                uploadTask.stopUpload();
                uploadTask.deleteTempFile();

                uploadTask.getListener().progress(0, 0, 4);

                iterator.remove();
            }
        }

        Iterator<UploadTask> iterator1 = waitingQueue.iterator();
        while (iterator1.hasNext()) {
            UploadTask uploadTask = iterator1.next();
            if (uploadTask.getZipFilePath().equals(filePath)) {
                LogUtil.e(TAG, "找到waiting任务，开始停止" + filePath);

                uploadTask.getListener().progress(0, 0, 4);

                iterator1.remove();
            }
        }

        doNext();
    }

    private void cancelServer(String filePath, String savePath, IHttpCallbackInterface httpCallbackInterface) {
        //调用后台接口，后台删除缓存文件完成取消上传。
        ZoomWebControler.getInstance().cancelBlockUpload(filePath, savePath, httpCallbackInterface);
    }

    @Subscribe
    public void onEvent(BlockUploadTaskEvent event) {
        Log.e(TAG, "有一个task执行成功了： " + event.getTag());
        Iterator<UploadTask> iterator = doingQueue.iterator();
        while (iterator.hasNext()) {
            UploadTask next = iterator.next();
            if (next.getTag().equals(event.getTag())) {
                iterator.remove();
                Log.e(TAG, "doingSize: " + doingQueue.size());
                Log.e(TAG, "onEvent: doing删掉一个");
            }
        }
        doNext();
    }

    private UploadTask pollTask() {
        int size = waitingQueue.size();
        if (size != 0) {
            UploadTask uploadTask = waitingQueue.get(0);
            waitingQueue.remove(0);
            return uploadTask;
        }
        return null;
    }

}
